
package com.cfpl.admin_service.controller;

import cn.hutool.json.JSONUtil;
import com.cfpl.admin_service.VO.DueRecord;
import com.cfpl.admin_service.VO.PlantAndVegTableInfo;
import com.cfpl.admin_service.VO.PlantLocationVO;
import com.cfpl.config.RedisUtils;
import com.cfpl.admin_service.mapper.*;
import com.cfpl.admin_service.service.FertilizerService;
import com.cfpl.admin_service.service.PesticideTypeService;
import com.cfpl.project_common.constant.RedisConstants;
import com.cfpl.project_common.enums.CodeEnum;
import com.cfpl.project_common.exception.BusException;
import com.cfpl.project_common.pojo.*;
import com.cfpl.project_common.result.BaseResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @Auther: LYP
 * @Date: 2023/10/25 - 17:29
 * @Description: com.cfpl.admin_service.controller
 * @version: 1.0
 */
@RestController
@Slf4j
@RequestMapping("/warning")
@Api(tags="预警管理相关接口")
public class WarningController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private FertilizerMapper fertilizerMapper;
    @Autowired
    private FertilizerService fertilizerService;
    @Autowired
    private PesticideTypeService pesTypeService;
    @Autowired
    private PesticideTypeMapper pesticideTypeMapper;
    @Autowired
    private PesticideUsageRecordMapper pesticideUsageRecordMapper;
    @Autowired
    private PlantingLocationMapper  plantingLocationMapper;
    @Autowired
    private VegetableMapper vegetableMapper;
    @Autowired
    private FertilizerUsageRecordsMapper  fertilizerUsageRecordsMapper;

    @ApiOperation("查询预警信息数量")
    @GetMapping("/queryNumOfWarning")
    public BaseResult<Map<String,Integer>> queryNumOfWarning(){

        Map<String,Integer> numMap = new HashMap();
        try {
            String jsonOfFertilizerNum = stringRedisTemplate.opsForValue().get(RedisConstants.WARNING_NUM_FERTILIZER);
            String jsonOfPesticideNum = stringRedisTemplate.opsForValue().get(RedisConstants.WARNING_NUM_PESTICIDE);
            String jsonOfDueFertilizerNum = stringRedisTemplate.opsForValue().get(RedisConstants.WARNING_NUM_DUE_FERTILIZER);
            String jsonOfDuePesticideNum = stringRedisTemplate.opsForValue().get(RedisConstants.WARNING_NUM_DUE_PESTICIDE);
            numMap.put("fertilizerNum",Integer.parseInt(Objects.requireNonNull(jsonOfFertilizerNum)));
            numMap.put("pesticideNum",Integer.parseInt(Objects.requireNonNull(jsonOfPesticideNum)));
            numMap.put("dueFertilizerNum",Integer.parseInt(Objects.requireNonNull(jsonOfDueFertilizerNum)));
            numMap.put("duePesticideNum ",Integer.parseInt(Objects.requireNonNull(jsonOfDuePesticideNum)));
        }catch (NullPointerException e){
            throw new BusException(CodeEnum.SUCCESS);
        }
        return BaseResult.ok(numMap);
    }

    @ApiOperation("查询农药或者肥料的库存预警列表")
    @GetMapping("/queryListOfWarningByName/{name}")
    public BaseResult queryListOfWarningByName(@PathVariable("name") String name){
        if (name.equals("fertilizer")){
            String jsonOfFertilizerList = stringRedisTemplate.opsForValue().get(RedisConstants.WARNING_STOCK_FERTILIZER);
            List<Fertilizer> fertilizerList = JSONUtil.toList(jsonOfFertilizerList, Fertilizer.class);
            return BaseResult.ok(fertilizerList);
        }else if (name.equals("pesticide")){
            String jsonOfPesticideList = stringRedisTemplate.opsForValue().get(RedisConstants.WARNING_STOCK_PESTICIDE);
            List<PesticideType> pesticideTypeList = JSONUtil.toList(jsonOfPesticideList, PesticideType.class);
            return BaseResult.ok(pesticideTypeList);
        }
        return BaseResult.ok();
    }

    @ApiOperation("查询低于设置阈值天数的农药或者肥料使用记录的预警信息列表")
    @GetMapping("/queryDueListByName/{name}")
    public BaseResult queryListOfDueByName(@PathVariable("name") String name){
        if (name.equals("fertilizer")){
            String jsonOfDueFertilizerRecord = stringRedisTemplate.opsForValue().get(RedisConstants.WARNING_DUE_RECORD_FERTILIZER);
            List<DueRecord> dueRecords = JSONUtil.toList(jsonOfDueFertilizerRecord, DueRecord.class);
            return BaseResult.ok(dueRecords);
        }else if (name.equals("pesticide")){
            String jsonOfPesticideList = stringRedisTemplate.opsForValue().get(RedisConstants.WARNING_DUE_RECORD_PESTICIDE);
            List<DueRecord> dueRecords = JSONUtil.toList(jsonOfPesticideList, DueRecord.class);
            return BaseResult.ok(dueRecords);
        }

        return BaseResult.ok();
    }

    /**
     * 更新肥料库存不足
     * 更新页面 和 更新前要查询的请求可以走FertilizerController
     * 但是点击更新的请求要走这个，因为更新完之后还要去删掉redis中的数据，以便返回主页面时查询出来的预警数据时最新的，如果不删除就只能等待定时任务自动刷新
     * @param fertilizer
     * @return
     */
    @ApiOperation("更新肥料库存不足")
    @PostMapping("/updateInsufficientStock/fertilizer")
    public BaseResult updateInsufficientStockOfFertilizer(@RequestBody Fertilizer fertilizer){

        fertilizerMapper.updateById(fertilizer);
        String jsonOfFertilizerList = stringRedisTemplate.opsForValue().get(RedisConstants.WARNING_STOCK_FERTILIZER);
        List<Fertilizer> fertilizerList = JSONUtil.toList(jsonOfFertilizerList, Fertilizer.class);
        for (Fertilizer item : fertilizerList) {
            //找到这个库存不足的记录，删掉重建
            if (item.getId().equals(fertilizer.getId())){
                fertilizerList.remove(item);
                break;
            }
        }
        //重写记录条数和记录
        RedisUtils.stringRedisTemplate.opsForValue().set(RedisConstants.WARNING_STOCK_FERTILIZER
                ,JSONUtil.toJsonStr(fertilizerList));
        RedisUtils.stringRedisTemplate.opsForValue().set(RedisConstants.WARNING_NUM_FERTILIZER
                ,String.valueOf(fertilizerList.size()));

        return BaseResult.ok();
    }

    //策略和肥料相同
    @ApiOperation("更新农药库存不足")
    @PostMapping("/updateInsufficientStock/pesticide")
    public BaseResult updateInsufficientStockOfPesticideType(@RequestBody PesticideType pesticideType){

        pesticideTypeMapper.updateById(pesticideType);
        String jsonOfPesticideList = stringRedisTemplate.opsForValue().get(RedisConstants.WARNING_STOCK_PESTICIDE);
        List<PesticideType> pesticideTypeList = JSONUtil.toList(jsonOfPesticideList, PesticideType.class);
        for (PesticideType item : pesticideTypeList) {
            //找到这个库存不足的记录，删掉重建
            if (item.getId().equals(pesticideType.getId())){
                pesticideTypeList.remove(item);
                break;
            }
        }
        //重写记录条数和记录
        RedisUtils.stringRedisTemplate.opsForValue().set(RedisConstants.WARNING_STOCK_FERTILIZER
                ,JSONUtil.toJsonStr(pesticideTypeList));
        RedisUtils.stringRedisTemplate.opsForValue().set(RedisConstants.WARNING_NUM_FERTILIZER
                ,String.valueOf(pesticideTypeList.size()));

        return BaseResult.ok();
    }


    @ApiOperation("肥效期预警数据的种植地点果蔬信息")
    @GetMapping("/queryLocationByFertilizerUseId/{id}")
    public BaseResult<PlantAndVegTableInfo> queryLocationByFertilizerUseId(@PathVariable("id") Long furid){
        PlantLocationVO plantLocationVO = plantingLocationMapper.queryLocationByFertilizerUseId(furid);
        Vegetable vegetable = vegetableMapper.queryVegetableByFertilizerUseId(furid);
        PlantAndVegTableInfo plantAndVegTableInfo = new PlantAndVegTableInfo(plantLocationVO,vegetable);
        return BaseResult.ok(plantAndVegTableInfo);
    }
    @ApiOperation("农药期预警数据的种植地点果蔬信息")
    @GetMapping("/queryLocationByPesticideUseId/{id}")
    public BaseResult<PlantAndVegTableInfo> queryLocationByPesticideUseId(@PathVariable("id") Long purid){
        PlantLocationVO plantLocationVO = plantingLocationMapper.queryLocationByPesticideUseId(purid);
        Vegetable vegetable = vegetableMapper.queryVegetableByPesticideUseId(purid);
        PlantAndVegTableInfo plantAndVegTableInfo = new PlantAndVegTableInfo(plantLocationVO,vegetable);
        return BaseResult.ok(plantAndVegTableInfo);
    }



    /**
     * 解决到期预警，点击去添加新的肥料或者农药，添加之后把表中这次预警记录的过期字段改为已处理 1
     * @param previousId 预警过期的记录ID
     * @param fertilizerUsageRecords 本次添加的使用记录
     * @return
     */
    @ApiOperation("解决肥效期到期")
    @PostMapping("/insertFertilizerUsageRecord")
    public BaseResult insertFertilizerUsageRecord(@RequestParam Long previousId,@RequestBody FertilizerUsageRecords fertilizerUsageRecords){
        //设置新的肥料使用记录，将旧的状态改为1,再将Redis中的过期记录删除,最后缓存重建
        fertilizerService.insertFertilizerUsageRecord(fertilizerUsageRecords);
        fertilizerUsageRecordsMapper.updateProcessed(previousId);
        String jsonOfDueFertilizerRecord = stringRedisTemplate.opsForValue().get(RedisConstants.WARNING_DUE_RECORD_FERTILIZER);
        List<DueRecord> dueRecords = JSONUtil.toList(jsonOfDueFertilizerRecord, DueRecord.class);
        for (DueRecord item : dueRecords) {
            //找到要解决的这一项
            if (item.getId().equals(previousId)){
                dueRecords.remove(item);
            }
            break;
        }
        //重写记录条数和记录
        RedisUtils.stringRedisTemplate.opsForValue().set(RedisConstants.WARNING_DUE_RECORD_FERTILIZER
                ,JSONUtil.toJsonStr(dueRecords));
        RedisUtils.stringRedisTemplate.opsForValue().set(RedisConstants.WARNING_NUM_DUE_FERTILIZER
                ,String.valueOf(dueRecords.size()));
        return BaseResult.ok();
    }


    /**
     * 解决到期预警，点击去添加新的肥料或者农药，添加之后把表中这次预警记录的过期字段改为已处理 1
     * @param previousId 预警过期的记录ID
     * @param pesUsaRecord 本次添加的使用记录
     * @return
     */
    @ApiOperation("解决农药到期")
    @PostMapping("/addPesticideUsageRecord")
    public BaseResult addPesticideUsageRecord(@RequestParam Long previousId,@RequestBody PesticideUsageRecord pesUsaRecord){
        //设置新的农药使用记录，将旧的状态改为1,再将Redis中的过期记录删除,最后缓存重建
        pesTypeService.addPesticideUsageRecord(pesUsaRecord);
        pesticideUsageRecordMapper.updateProcessed(previousId);
        String jsonOfDuePesticideRecord = stringRedisTemplate.opsForValue().get(RedisConstants.WARNING_DUE_RECORD_PESTICIDE);
        List<DueRecord> dueRecords = JSONUtil.toList(jsonOfDuePesticideRecord, DueRecord.class);
        for (DueRecord item : dueRecords) {
            //找到要解决的这一项
            if (item.getId().equals(previousId)){
                dueRecords.remove(item);
            }
            break;
        }
        //重写记录条数和记录
        RedisUtils.stringRedisTemplate.opsForValue().set(RedisConstants.WARNING_DUE_RECORD_PESTICIDE
                ,JSONUtil.toJsonStr(dueRecords));
        RedisUtils.stringRedisTemplate.opsForValue().set(RedisConstants.WARNING_NUM_DUE_PESTICIDE
                ,String.valueOf(dueRecords.size()));
        return BaseResult.ok();
    }





}
